/// 视频集合数据模型
/// 用于管理用户创建的视频集合

/// 视频集合模型 - 对应数据库 matrix_user_collections 表
class CollectionModel {
  /// 集合ID
  final int id;
  
  /// 创建者用户ID
  final int userId;
  
  /// 集合标题
  final String title;
  
  /// 集合描述/简介
  final String? description;
  
  /// 集合封面图URL
  final String? coverUrl;
  
  /// 分类ID
  final String? categoryId;
  
  /// 分类名称
  final String? categoryName;
  
  /// 标签数组
  final List<String> tags;
  
  /// 视频数量
  final int videoCount;
  
  /// 总时长（秒）
  final int totalDuration;
  
  /// 浏览次数
  final int viewsCount;
  
  /// 点赞数
  final int likesCount;
  
  /// 访问类型：public-公开，whitelist-白名单
  final String accessType;
  
  /// 状态：draft-草稿，published-已发布，hidden-隐藏
  final String status;
  
  /// 是否用户付费推荐
  final bool isRecommended;
  
  /// 推荐过期时间
  final DateTime? recommendExpireTime;
  
  /// 创建时间
  final DateTime createTime;
  
  /// 更新时间
  final DateTime updateTime;
  
  /// 创建者用户名（关联查询）
  final String? userNickname;
  
  /// 创建者头像（关联查询）
  final String? userAvatar;

  CollectionModel({
    required this.id,
    required this.userId,
    required this.title,
    this.description,
    this.coverUrl,
    this.categoryId,
    this.categoryName,
    this.tags = const [],
    this.videoCount = 0,
    this.totalDuration = 0,
    this.viewsCount = 0,
    this.likesCount = 0,
    this.accessType = 'public',
    this.status = 'draft',
    this.isRecommended = false,
    this.recommendExpireTime,
    required this.createTime,
    required this.updateTime,
    this.userNickname,
    this.userAvatar,
  });

  /// 从JSON创建模型
  factory CollectionModel.fromJson(Map<String, dynamic> json) {
    // 解析标签
    List<String> parseTags(dynamic tagsData) {
      if (tagsData == null) return [];
      if (tagsData is List) {
        return tagsData.map((e) => e.toString()).toList();
      }
      if (tagsData is String && tagsData.isNotEmpty) {
        try {
          // 尝试解析JSON字符串
          return tagsData.split(',').map((e) => e.trim()).toList();
        } catch (e) {
          return [];
        }
      }
      return [];
    }

    return CollectionModel(
      id: json['id'] ?? 0,
      userId: json['userId'] ?? json['user_id'] ?? 0,
      title: json['title'] ?? '',
      description: json['description'],
      coverUrl: json['coverUrl'] ?? json['cover_url'],
      categoryId: json['categoryId'] ?? json['category_id'],
      categoryName: json['categoryName'] ?? json['category_name'],
      tags: parseTags(json['tags']),
      videoCount: json['videoCount'] ?? json['video_count'] ?? 0,
      totalDuration: json['totalDuration'] ?? json['total_duration'] ?? 0,
      viewsCount: json['viewsCount'] ?? json['views_count'] ?? 0,
      likesCount: json['likesCount'] ?? json['likes_count'] ?? 0,
      accessType: json['accessType'] ?? json['access_type'] ?? 'public',
      status: json['status'] ?? 'draft',
      isRecommended: json['isRecommended'] ?? json['is_recommended'] ?? false,
      recommendExpireTime: json['recommendExpireTime'] != null 
          ? DateTime.parse(json['recommendExpireTime']) 
          : (json['recommend_expire_time'] != null 
              ? DateTime.parse(json['recommend_expire_time']) 
              : null),
      createTime: json['createTime'] != null 
          ? DateTime.parse(json['createTime']) 
          : (json['create_time'] != null 
              ? DateTime.parse(json['create_time']) 
              : DateTime.now()),
      updateTime: json['updateTime'] != null 
          ? DateTime.parse(json['updateTime']) 
          : (json['update_time'] != null 
              ? DateTime.parse(json['update_time']) 
              : DateTime.now()),
      // 后端返回的是 authorNickname/authorAvatar，兼容多种字段名
      userNickname: json['authorNickname'] ?? json['author_nickname'] ?? json['userNickname'] ?? json['user_nickname'],
      userAvatar: json['authorAvatar'] ?? json['author_avatar'] ?? json['userAvatar'] ?? json['user_avatar'],
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'userId': userId,
      'title': title,
      'description': description,
      'coverUrl': coverUrl,
      'categoryId': categoryId,
      'categoryName': categoryName,
      'tags': tags,
      'videoCount': videoCount,
      'totalDuration': totalDuration,
      'viewsCount': viewsCount,
      'likesCount': likesCount,
      'accessType': accessType,
      'status': status,
      'isRecommended': isRecommended,
      'recommendExpireTime': recommendExpireTime?.toIso8601String(),
      'createTime': createTime.toIso8601String(),
      'updateTime': updateTime.toIso8601String(),
      'userNickname': userNickname,
      'userAvatar': userAvatar,
    };
  }

  /// 获取格式化的总时长
  String get formattedDuration {
    final hours = totalDuration ~/ 3600;
    final minutes = (totalDuration % 3600) ~/ 60;
    final seconds = totalDuration % 60;
    
    if (hours > 0) {
      return '${hours}小时${minutes}分钟';
    } else if (minutes > 0) {
      return '${minutes}分${seconds}秒';
    } else {
      return '${seconds}秒';
    }
  }

  /// 获取访问类型显示文本
  String get accessTypeText {
    switch (accessType) {
      case 'public':
        return '公开';
      case 'whitelist':
        return '白名单';
      default:
        return '公开';
    }
  }

  /// 获取状态显示文本
  String get statusText {
    switch (status) {
      case 'draft':
        return '草稿';
      case 'published':
        return '已发布';
      case 'hidden':
        return '已隐藏';
      default:
        return '未知';
    }
  }

  /// 是否是公开集合
  bool get isPublic => accessType == 'public';

  /// 是否是白名单集合
  bool get isWhitelist => accessType == 'whitelist';

  /// 是否已发布
  bool get isPublished => status == 'published';

  /// 复制并修改
  CollectionModel copyWith({
    int? id,
    int? userId,
    String? title,
    String? description,
    String? coverUrl,
    String? categoryId,
    String? categoryName,
    List<String>? tags,
    int? videoCount,
    int? totalDuration,
    int? viewsCount,
    int? likesCount,
    String? accessType,
    String? status,
    bool? isRecommended,
    DateTime? recommendExpireTime,
    DateTime? createTime,
    DateTime? updateTime,
    String? userNickname,
    String? userAvatar,
  }) {
    return CollectionModel(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      title: title ?? this.title,
      description: description ?? this.description,
      coverUrl: coverUrl ?? this.coverUrl,
      categoryId: categoryId ?? this.categoryId,
      categoryName: categoryName ?? this.categoryName,
      tags: tags ?? this.tags,
      videoCount: videoCount ?? this.videoCount,
      totalDuration: totalDuration ?? this.totalDuration,
      viewsCount: viewsCount ?? this.viewsCount,
      likesCount: likesCount ?? this.likesCount,
      accessType: accessType ?? this.accessType,
      status: status ?? this.status,
      isRecommended: isRecommended ?? this.isRecommended,
      recommendExpireTime: recommendExpireTime ?? this.recommendExpireTime,
      createTime: createTime ?? this.createTime,
      updateTime: updateTime ?? this.updateTime,
      userNickname: userNickname ?? this.userNickname,
      userAvatar: userAvatar ?? this.userAvatar,
    );
  }

  @override
  String toString() {
    return 'CollectionModel(id: $id, title: $title, videoCount: $videoCount, status: $status)';
  }
}

/// 集合内视频模型 - 对应数据库 matrix_collection_videos 表
class CollectionVideoModel {
  /// 视频ID
  final int id;
  
  /// 所属集合ID
  final int collectionId;
  
  /// 视频标题
  final String title;
  
  /// 视频描述
  final String? description;
  
  /// 视频URL
  final String videoUrl;
  
  /// 封面图URL
  final String? coverUrl;
  
  /// 视频时长（秒）
  final int duration;
  
  /// 排序序号
  final int orderNo;
  
  /// 播放次数
  final int playCount;
  
  /// 创建时间
  final DateTime createTime;
  
  /// 更新时间
  final DateTime updateTime;

  CollectionVideoModel({
    required this.id,
    required this.collectionId,
    required this.title,
    this.description,
    required this.videoUrl,
    this.coverUrl,
    this.duration = 0,
    this.orderNo = 0,
    this.playCount = 0,
    required this.createTime,
    required this.updateTime,
  });

  /// 从JSON创建模型
  factory CollectionVideoModel.fromJson(Map<String, dynamic> json) {
    return CollectionVideoModel(
      id: json['id'] ?? 0,
      collectionId: json['collectionId'] ?? json['collection_id'] ?? 0,
      title: json['title'] ?? '',
      description: json['description'],
      videoUrl: json['videoUrl'] ?? json['video_url'] ?? '',
      coverUrl: json['coverUrl'] ?? json['cover_url'],
      // 后端返回的是 durationSec，兼容两种字段名
      duration: json['durationSec'] ?? json['duration_sec'] ?? json['duration'] ?? 0,
      orderNo: json['orderNo'] ?? json['order_no'] ?? 0,
      // 后端返回的是 viewsCount，兼容两种字段名
      playCount: json['viewsCount'] ?? json['views_count'] ?? json['playCount'] ?? json['play_count'] ?? 0,
      createTime: json['createTime'] != null 
          ? DateTime.parse(json['createTime']) 
          : (json['create_time'] != null 
              ? DateTime.parse(json['create_time']) 
              : DateTime.now()),
      updateTime: json['updateTime'] != null 
          ? DateTime.parse(json['updateTime']) 
          : (json['update_time'] != null 
              ? DateTime.parse(json['update_time']) 
              : DateTime.now()),
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'collectionId': collectionId,
      'title': title,
      'description': description,
      'videoUrl': videoUrl,
      'coverUrl': coverUrl,
      'duration': duration,
      'orderNo': orderNo,
      'playCount': playCount,
      'createTime': createTime.toIso8601String(),
      'updateTime': updateTime.toIso8601String(),
    };
  }

  /// 获取格式化的时长
  String get formattedDuration {
    final minutes = duration ~/ 60;
    final seconds = duration % 60;
    return '${minutes.toString().padLeft(2, '0')}:${seconds.toString().padLeft(2, '0')}';
  }

  /// 复制并修改
  CollectionVideoModel copyWith({
    int? id,
    int? collectionId,
    String? title,
    String? description,
    String? videoUrl,
    String? coverUrl,
    int? duration,
    int? orderNo,
    int? playCount,
    DateTime? createTime,
    DateTime? updateTime,
  }) {
    return CollectionVideoModel(
      id: id ?? this.id,
      collectionId: collectionId ?? this.collectionId,
      title: title ?? this.title,
      description: description ?? this.description,
      videoUrl: videoUrl ?? this.videoUrl,
      coverUrl: coverUrl ?? this.coverUrl,
      duration: duration ?? this.duration,
      orderNo: orderNo ?? this.orderNo,
      playCount: playCount ?? this.playCount,
      createTime: createTime ?? this.createTime,
      updateTime: updateTime ?? this.updateTime,
    );
  }

  @override
  String toString() {
    return 'CollectionVideoModel(id: $id, title: $title, duration: $duration)';
  }
}

/// 白名单用户模型 - 对应数据库 matrix_collection_whitelist 表
class WhitelistUserModel {
  /// 记录ID
  final int id;
  
  /// 集合ID
  final int collectionId;
  
  /// 被授权用户ID
  final int userId;
  
  /// 被授权用户名
  final String? username;
  
  /// 被授权用户头像
  final String? userAvatar;
  
  /// 授权时间
  final DateTime createTime;
  
  /// 授权备注
  final String? remark;

  WhitelistUserModel({
    required this.id,
    required this.collectionId,
    required this.userId,
    this.username,
    this.userAvatar,
    required this.createTime,
    this.remark,
  });

  /// 从JSON创建模型
  factory WhitelistUserModel.fromJson(Map<String, dynamic> json) {
    return WhitelistUserModel(
      id: json['id'] ?? 0,
      collectionId: json['collectionId'] ?? json['collection_id'] ?? 0,
      userId: json['userId'] ?? json['user_id'] ?? 0,
      username: json['username'],
      userAvatar: json['userAvatar'] ?? json['user_avatar'],
      createTime: json['createTime'] != null 
          ? DateTime.parse(json['createTime']) 
          : (json['create_time'] != null 
              ? DateTime.parse(json['create_time']) 
              : DateTime.now()),
      remark: json['remark'],
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'collectionId': collectionId,
      'userId': userId,
      'username': username,
      'userAvatar': userAvatar,
      'createTime': createTime.toIso8601String(),
      'remark': remark,
    };
  }

  @override
  String toString() {
    return 'WhitelistUserModel(id: $id, userId: $userId, username: $username)';
  }
}
